<template>
  <div class="details">
    <!-- 导航条 -->
    <div class="details-nav" v-if="type !== 'normal'">
      <ul>
        <li @click="scroll('topA')">
          <a href="javascript:;">商品</a>
        </li>
        <li @click="scroll('sku')">
          <a href="javascript:;">评价</a>
        </li>
        <li @click="scroll('detail')">
          <a href="javascript:;">详情</a>
        </li>
      </ul>
    </div>
    <div class="details_input" v-else>
      <input type="text" placeholder="输入关键字" />
    </div>
    <!-- 轮播图 -->
    <div class="swiper" ref="topA">
      <van-swipe
        class="sliderImages"
        :autoplay="3000"
        indicator-color="red"
      >
        <van-swipe-item
          v-for="slider in sliderImages.slice(1)"
          :key="slider.id"
        >
          <img :src="slider" />
        </van-swipe-item>
      </van-swipe>
    </div>

    <sec-info :list="basicInfo" v-if="type == 'seckill'"></sec-info>
    <pin-tuan-hui :pt="basicInfo" v-if="type == 'pt'"></pin-tuan-hui>
    <pu-tong :putong="basicInfo" v-if="type == 'normal'"></pu-tong>

    <!-- 商品规格 -->
    <div
      ref="sku"
      class="sku targetScroll"
      v-if="Object.keys(curSku).length"
      @click="show = !show"
    >
      <p>已选择:</p>
      <div class="sku-info">
        <p>
          <span>{{ Object.keys(curSku)[0] }}</span
          ><span>&gt;</span>
        </p>
        <div>
          <img v-for="(src, i) in skuImgs" :key="i" :src="src" alt="" />
          <span>共{{ totalSkus }}种规格可选</span>
        </div>
      </div>
    </div>
    <!--  动作面板种的自定义面板 弹出框-->
    <van-action-sheet v-model="show">
      <div class="content">
        <div class="cheader">
          <img :src="Object.values(curSku)[0].image" alt="" />
          <div class="cheader-info">
            <h3>{{ basicInfo.storeName }}</h3>
            <h2>￥{{ Object.values(curSku)[0].price }}</h2>
            <p>库存:{{ Object.values(curSku)[0].stock }}</p>
          </div>
        </div>
        <!-- 规格 -->
        <div class="skus">
          <div
            class="sku-info"
            v-for="(sku, j) in goodsInfo.productAttr"
            :key="sku.id"
          >
            <h3>{{ sku.attrName }}</h3>
            <ul>
              <li
                :class="{
                  active: Object.keys(curSku)[0].split(',')[j] === attr,
                }"
                v-for="attr in sku.attrValues.split(',')"
                :key="attr"
                @click="setCurSku(attr, j)"
              >
                {{ attr }}
              </li>
            </ul>
          </div>
        </div>
      </div>
    </van-action-sheet>
    <!-- 商品详情 -->
    <div ref="detail" class="details_data">
      <h3>产品详情</h3>
      <div v-html="detailStr"></div>
    </div>

    <!-- 底部tarbar -->
    <div class="tarbar">
      <div class="service">
        <van-goods-action>
          <van-goods-action-icon icon="chat-o" text="客服" color="#ee0a24" />
          <van-goods-action-icon icon="cart-o" text="购物车" />
          <van-goods-action-icon icon="star" text="已收藏" color="#ff5000" />
          <van-goods-action-button
            type="warning"
            text="加入购物车"
            color="#be99ff"
          />
          <van-goods-action-button
            type="danger"
            text="立即购买"
            color="#7232dd"
          />
        </van-goods-action>
      </div>
    </div>
  </div>
</template>

<script>
import SecInfo from "@/components/SecInfo.vue";
import PinTuanHui from "@/components/PinTuanHui.vue";
import PuTong from "@/components/PuTong.vue";
export default {
  name: "DetailsAll",

  data() {
    return {
      id: "",
      type: "", // 详情页类型：秒杀、拼团惠、普通商品
      goodsInfo: null, // 商品
      sliderImages: [], // 轮播图数据
      basicInfo: {}, // 详情页不同信息
      // 组件
      show: false,
      sku: {
        tree: [],
        list: [
          {
            id: 2259, // skuId
            s1: "1", // 规格类目 k_s 为 s1 的对应规格值 id
            s2: "1", // 规格类目 k_s 为 s2 的对应规格值 id
            price: 100, // 价格（单位分）
            stock_num: 110, // 当前 sku 组合对应的库存
          },
        ],
      },
      goods: {},
      goodsId: 1,
      quota: 100,
      quotaUsed: 10,

      skuImgs: [], // 存规格缩略图的变量
      totalSkus: 0, // 规格的总数量
      curSku: {}, // 默认选中展示的规格

      detailStr: "", // 商品详情介绍
      initImgWidth: true, // 产品详情的v-html的图片
      // nums: 1, // 购物车数量
    };
  },

  created() {
    this.id = this.$route.params.id;
    this.type = this.$route.query.type;
    var url = null;
    switch (this.type) {
      case "seckill":
        url = `/crmeb/seckill/detail/${this.id}`;
        break;
      case "pt":
        url = `/crmeb/combination/detail/${this.id}`;
        break;
      case "normal":
        url = `/crmeb/product/detail/${this.id}?type=normal`;
        break;
    }

    this.$axios(url).then((data) => {
      this.goodsInfo = data.data.data;
      // console.log(this.goodsInfo, data);
      if (this.type == "seckill") {
        const res = this.goodsInfo.storeSeckill;
        this.sliderImages = JSON.parse(res.sliderImage);
        this.basicInfo = {
          storeName: res.storeName,
          sales: res.sales,
          ficti: res.ficti,
          quota: res.quota,
          unitName: res.unitName,
        };
        this.detailStr = res.content;
      } else if (this.type == "pt") {
        const res = this.goodsInfo.storeCombination;
        this.detailStr = res.content;
        this.sliderImages = JSON.parse(res.sliderImage);
        this.basicInfo = {
          price: res.price,
          otPrice: res.otPrice,
          storeName: res.storeName,
          people: res.people,
          ficti: res.ficti,
          sales: res.sales,
          unitName: res.unitName,
        };
      } else if (this.type == "normal") {
        const res = this.goodsInfo.productInfo;
        this.detailStr = res.content;
        this.sliderImages = JSON.parse(res.sliderImage);
        this.basicInfo = {
          price: res.price,
          storeName: res.storeName,
          sales: res.sales,
          stock: res.stock,
          otPrice: res.otPrice,
          unitName: res.unitName,
        };
      }
      this.goodsInfo.productAttr.forEach((sku) => {
        let skuObj = {
          k: sku.attrName,
          k_s: "s1",
          v: [],
        };
        sku.attrValues.split(",").forEach((s) => {
          skuObj.v.push({
            id: "1",
            name: s,
          });
        });
        this.sku.tree.push(skuObj);
      });
      // 处理页面中已选择部分：默认选中规格和规格缩略图
      const skuItems = this.goodsInfo.productValue;
      this.totalSkus = Object.keys(skuItems).length;
      Object.keys(skuItems)
        .slice(0, 4)
        .forEach((sku) => {
          this.skuImgs.push(skuItems[sku].image);
        });
      this.curSku[Object.keys(skuItems)[0]] =
        skuItems[Object.keys(skuItems)[0]];
    });

    this.$axios
      .get(
        "https://apif.java.crmeb.net/api/front/cart/count?numType=true&type=total"
      )
      .then(({ data }) => {
        this.nums = data.data.count;
      });
  },

  updated() {
    // 设置img(v-html)图片尺寸 但是这个updata()会执行多次 用布尔值控制一下
    if (this.initImgWidth) {
      // Array.from() 把对象转成数组
      Array.from(document.querySelectorAll(".details_data img")).forEach(
        (img) => {
          img.style.width = "100vw";
        }
      );
      this.initImgWidth = false;
    }
  },
  methods: {
    setCurSku(attr, idx) {
      console.log(attr); // 点击那个获取到那个
      const oldKeys = Object.keys(this.curSku)[0].split(",");
      oldKeys[idx] = attr;
      // console.log(oldKeys, idx);  // 点击呢个控制台出现一套配置
      // console.log(oldKeys);
      const newKeys = oldKeys.join(","); // 数组拼成字符串
      this.curSku = {
        [newKeys]: this.goodsInfo.productValue[newKeys],
      };
    },
    scroll(id){
      // console.log(this.$refs);
      this.$refs[id].scrollIntoView(true)    // 替代锚点定位
    }
  },

  components: {
    SecInfo,
    PinTuanHui,
    PuTong,
  },
};
</script>

<style lang="scss" scoped>
.details {
  height: calc(100vh - 52px);
  overflow-y: scroll;
  &::-webkit-scrollbar {
    display: none;
  }
  .details-nav {
    position: sticky;
    top: -1px;
    left: 0;
    z-index: 1000;
    background-color: antiquewhite;
    ul {
      height: 50px;
      display: flex;
      justify-content: space-around;
      align-items: center;
      li {
        font-size: 14px;
      }
    }
  }

  .swiper {
    img {
      width: 375px;
      height: 373px;
    }
  }
  /* 规格 */
  .sku {
    width: 90vw;
    margin: 0 auto;
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    > p {
      width: 70px;
    }
    > div {
      width: calc(100% - 70px);
      > p {
        display: flex;
        justify-content: space-between;
      }
      > div {
        display: flex;
        align-items: center;
      }
      img {
        width: 33px;
        height: 33px;
      }
    }
  }
  .van-action-sheet__content {
    &::-webkit-scrollbar {
      display: none;
    }
  }
  /* 弹出框 */
  .content {
    padding: 10px;
    .cheader {
      display: flex;
      justify-content: space-between;
      img {
        width: 75px;
        height: 75px;
      }
      h3 {
        width: 280px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
    .skus {
      .sku-info {
        margin: 20px 0;
        h3 {
          height: 30px;
          line-height: 30px;
        }
        ul {
          display: flex;
          flex-wrap: wrap;
          li {
            font-size: 14px;
            padding: 5px 10px;
            border-radius: 15px;
            background-color: lightblue;
            margin-right: 10px;
            margin-bottom: 10px;
            &.active {
              color: blue;
              border: 1px solid blue;
            }
          }
        }
      }
    }
  }
  /* 产品详情 */
  .details_data {
    margin-top: 20px;
    h3 {
      height: 40px;
      line-height: 40px;
      text-align: center;
    }
  }
  /* 底部tarbar */
  .tarbar {
    width: 100%;
    height: 50px;
    position: fixed;
    bottom: 0;
    background-color: rgb(173, 232, 35);
  }
}
</style>
